/************************************************************************
<4loco-aprs.  This program connects to a specified APRS server and displays
    the information on a map. It's being developed using QT Creator. The project
    began in February and version 1 should be released in April. For more
    information go to http://code.google.com/p/4loco-aprs/>

    Copyright (C) <2011>  <Kyle Roden, Glen Riden, Aaron Smith, Alisa Emerich>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

#include "conectionthread.h"
#include "aprsparser.h"
#include <QtSql>
#include "lightmaps.h"

ConnectionThread::ConnectionThread(QString server, int port, QString user, QString password, QString filter){

    connection = new QTcpSocket(this);
    connection->connectToHost(server, port);
    if (connection->waitForConnected(3000))
    {
        QByteArray sendString;
        sendString.append("user ");
        sendString.append(user);
        sendString.append(" pass ");
        sendString.append(password);
        sendString.append(" vers APRSAPP v1 filter ");
        sendString.append(filter);
        sendString.append("\n");
        qDebug()<<"Connection successful. Sending authorization string:"<<sendString;



        connection->write(sendString);

        connect(connection, SIGNAL(readyRead()), this, SLOT(getData()));
    }
    else
    {
        qDebug() << "Connect failed. Check settings and try again.";
    }



}


void ConnectionThread::run()
{

    exec();//start the event loop
}


void ConnectionThread::removeConnection(){

    connection->close();
    quit();
    delete connection;

}

void ConnectionThread::getData(){

    QTextStream buffer(connection);
    QString msg = buffer.readLine();

    QString hashMsg=msg;
    int i = hashMsg.indexOf(',');
    int j = hashMsg.indexOf(':');
    if(i<j)
        hashMsg.remove(i,j-i);
    if(packetHash.contains(hashMsg))
        return;
    packetHash.insert(hashMsg,' ');


    APRSParser a;
    enum result res;
    res = a.parse(msg);


    // THROW THE PACKET INTO THE DATABASE
    if (msg.data()[0] != '#') // make sure the packet isn't a commented packet
    {
        emit newPacket(a);

        QSqlQuery addNewData;
        addNewData.prepare("INSERT INTO packets VALUES (?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");

        addNewData.addBindValue(QDateTime::currentDateTime().toString("M-dd-yyyy hh.mm.ss.zzz"));
        addNewData.addBindValue(QDateTime::currentDateTime().toString("yyyyMMddhhmmss"));
        addNewData.addBindValue(QChar(a.symbolcode));
        addNewData.addBindValue(a.srccallsign);
        addNewData.addBindValue(a.dstcallsign);
        addNewData.addBindValue(a.latitude);
        addNewData.addBindValue(a.longitude);
        addNewData.addBindValue(a.altitude);
        addNewData.addBindValue(a.speed);
        addNewData.addBindValue(a.course);
        addNewData.addBindValue(a.posresolution);
        addNewData.addBindValue(a.temperature);
        addNewData.addBindValue(a.pressure);
        addNewData.addBindValue(a.wind_speed);
        addNewData.addBindValue(a.wind_direction);
        addNewData.addBindValue(a.wind_gust);
        addNewData.addBindValue(a.rain_1h);
        addNewData.addBindValue(a.rain_24h);
        addNewData.addBindValue(a.rain_midnight);
        addNewData.addBindValue(a.snow_24h);
        addNewData.addBindValue(a.raincount);
        addNewData.addBindValue(a.humidity);
        addNewData.addBindValue(a.luminosity);
        addNewData.addBindValue(a.data);
        addNewData.addBindValue(a.comment);
        addNewData.addBindValue(msg);
        addNewData.addBindValue(a.pktheader);
        addNewData.addBindValue(a.pktbody);
        if(!addNewData.exec())
            qDebug()<<addNewData.lastError()<<"error adding latest packet to db";
    }

}
